package com.lovetransferjia.chatuidemo.jia.fragment;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.beardedhen.androidbootstrap.BootstrapEditText;
import com.lovetransferjia.chatuidemo.R;

import com.lovetransferjia.chatuidemo.MyApplication;
import com.lovetransferjia.chatuidemo.jia.utility.Communicator;
import com.lovetransferjia.chatuidemo.jia.utility.Utility;
import com.nostra13.universalimageloader.core.ImageLoader;

import fr.castorflex.android.smoothprogressbar.SmoothProgressBar;

import android.R.bool;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ModifyInfoFragment extends Fragment {
	BootstrapEditText name,gender,bio,school,major,message;
	ImageView imageView,bgImageView;
	Button button,modifyimage;
	String nameString="",genderString="",hobbyString="",bioString="",cityString="",schoolString="",majorString="",messageString="";
	String locationString="";
	ImageLoader imageLoader;
	Communicator communicator;
	private static final int IMAGE_REQUEST_CODE = 1;
	private static final int CAMERA_REQUEST_CODE = 2;
	private static final int RESULT_REQUEST_CODE = 3;
	Bitmap photo;
	Boolean uploadEnabled=false;
	Boolean uploadSuccess=false;
	private SmoothProgressBar mPocketBar;
	

 	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		imageLoader=MyApplication.imageLoader;
		communicator =(Communicator) getActivity();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView;
		rootView = inflater.inflate(R.layout.jia_profile_modify, container, false);
		mPocketBar=(SmoothProgressBar) rootView.findViewById(R.id.progressBar);
		mPocketBar.setVisibility(View.INVISIBLE);
		name=(BootstrapEditText) rootView.findViewById(R.id.profile_name);		
		//hobby=(EditText) rootView.findViewById(R.id.profile_hobby);
		bio=(BootstrapEditText) rootView.findViewById(R.id.profile_bio);
		//city=(EditText) rootView.findViewById(R.id.profile_city);
		school=(BootstrapEditText) rootView.findViewById(R.id.profile_school);
		major=(BootstrapEditText) rootView.findViewById(R.id.profile_major);
		imageView= (ImageView) rootView.findViewById(R.id.imageView1);
		modifyimage=(Button) rootView.findViewById(R.id.button2);
		bgImageView=(ImageView) rootView.findViewById(R.id.imageView2);
		LayoutParams para;  
		para = bgImageView.getLayoutParams();  
		if(true)
		{
			DisplayMetrics dm = new DisplayMetrics();
			getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
			// 屏幕宽度
			int screenWidth = dm.widthPixels;
			MyApplication.screenWidth=screenWidth;
			// 屏幕高度
			int screenHeight = dm.heightPixels;
			Rect frame = new Rect();  
			getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);  
			int statusBarHeight = frame.top;
			final float scale = getActivity().getResources().getDisplayMetrics().density;
			para.height =(int) (screenHeight-(98)*scale-statusBarHeight);    
			para.width=screenWidth;
			bgImageView.setLayoutParams(para);
		}
		
		boolean getinfo=false;
		if(MyApplication.my_name!=null){
			name.setText(MyApplication.my_name);
		}else{ getinfo=true;}
		if(MyApplication.my_school!=null){
			school.setText(MyApplication.my_school);
		}else{ getinfo=true;}
		if(MyApplication.my_major!=null){
			major.setText(MyApplication.my_major);
		}else{ getinfo=true;}
		if(MyApplication.my_bio!=null){
			bio.setText(MyApplication.my_bio);
		}else{ getinfo=true;}
		if(MyApplication.my_img!=null){
			imageLoader.displayImage(MyApplication.my_img, imageView);
		}else{ getinfo=true;}
		if(getinfo){
			new GetInfo().execute(MyApplication.id);
		}
		
		
		
		modifyimage.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (uploadEnabled = true)
					new upload_image().execute();
			}
		});
		imageView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intentFromGallery = new Intent();
				intentFromGallery.setType("image/*"); // 设置文件类型
				intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
				startActivityForResult(intentFromGallery, IMAGE_REQUEST_CODE);
			}
		});
		
		
		button=(Button) rootView.findViewById(R.id.button1);
		button.setText("确认修改");
		button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Boolean flag=true;
				String str="";
				if(name.getText().toString().equals("")||name.getText().toString()==null){
					str="请输入姓名";
					flag=false;
				}
				if(bio.getText().toString().equals("")||bio.getText().toString()==null){
					str="请输入个性宣言";
					flag=false;
				}
				/*if(hobby.getText().toString().equals("")||hobby.getText().toString()==null){
					str="请输入爱好";
					flag=false;
				}*/
				if(school.getText().toString().equals("")||school.getText().toString()==null){
					str="请输入学校";
					flag=false;
				}
				if(major.getText().toString().equals("")||major.getText().toString()==null){
					str="请输入专业";
					flag=false;
				}
				/*if(city.getText().toString().equals("")||city.getText().toString()==null){
					str="请输入所在城市";
					flag=false;
				}
			*/
				
				if(flag==true)
					new PostInfo().execute();
				else {
					Toast.makeText(getActivity(), str, Toast.LENGTH_SHORT).show();
				}
			}
		});
		
		return rootView;
	}
	
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
	}
	

	public class GetInfo extends AsyncTask<String, Void, Boolean>{
		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			mPocketBar.setVisibility(View.INVISIBLE);
			if(result==true){
				
				name.setText(nameString);
			//	city.setText(cityString);
				bio.setText(bioString);
			//	hobby.setText(hobbyString);
				school.setText(schoolString);
				major.setText(majorString);
			
				imageLoader.displayImage(locationString, imageView);
			}
		}
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			mPocketBar.setVisibility(View.VISIBLE);
			super.onPreExecute();
		}
		String urlString=MyApplication.baseUrl+"user_info/info/"+"0"+"/0"+MyApplication.postfix;
		String failString="";
		@Override
		protected Boolean doInBackground(String... args) {
			urlString=MyApplication.baseUrl+"user_info/info/"+args[0]+"/0"+MyApplication.postfix;
			try {
				JSONObject jsonObject = Utility.GETObject(urlString, failString);
				nameString=jsonObject.getString("name");
				genderString=jsonObject.getString("gender");
				cityString=jsonObject.getString("city");
				schoolString=jsonObject.getString("school");
				majorString=jsonObject.getString("major");
				hobbyString=jsonObject.getString("hobby");
				bioString=jsonObject.getString("profile");
				locationString=jsonObject.getString("headimage");
				return true;
			}catch (Exception e)
			{
				Log.w("Getinfo",e.toString());
				failString=e.toString();
			}
			return false;
		}
		
	}

	public class PostInfo extends AsyncTask<String, Void, Boolean>{
			@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
				mPocketBar.setVisibility(View.INVISIBLE);
			super.onPostExecute(result);
			if(result==true){
				
				MyApplication.my_name=name.getText().toString();
				MyApplication.my_bio=bio.getText().toString();
				MyApplication.my_school=school.getText().toString();
				MyApplication.my_major=major.getText().toString();
				MyApplication.my_img=null;
				communicator.respond("go to myinfo");	
				/*MyApplication.city=city.getText().toString();
				MyApplication.hobby=hobby.getText().toString();*/
			}
		}
			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();
				mPocketBar.setVisibility(View.VISIBLE);
			}
			String urlString=MyApplication.baseUrl+"user_info/info.json";
			String statusString="",failString="";
		@Override
		protected Boolean doInBackground(String... args) {
			// TODO Auto-generated method stub
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("name",name.getText().toString()));
			params.add(new BasicNameValuePair("profile", bio.getText().toString()));
			params.add(new BasicNameValuePair("school", school.getText().toString()));
			params.add(new BasicNameValuePair("major",major.getText().toString()));
			/*params.add(new BasicNameValuePair("city",city.getText().toString()));
			params.add(new BasicNameValuePair("hobby",hobby.getText().toString()));*/
			try {
				JSONObject jsonObject = Utility.PostSimple(urlString, params,
						statusString, failString);
				if (jsonObject.getString("status").equals("success"))
					return true;
				else{
					failString=jsonObject.getString("status");
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				failString=e.toString();
			}
			return false;
		}
		
	}
	
	public class upload_image extends AsyncTask<String, Void, Boolean> {
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			mPocketBar.setVisibility(View.VISIBLE);
		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			mPocketBar.setVisibility(View.INVISIBLE);
			try {
				if (result == true) {
					Toast.makeText(getActivity(), statusString, Toast.LENGTH_LONG)
							.show();
					uploadSuccess=true;
				} else {
					Toast.makeText(getActivity(), statusString+" "+failString, Toast.LENGTH_LONG)
							.show();
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
		}

		String urlString = MyApplication.baseUrl
				+ "upload/upload.json";
		String statusString = "", failString = "";

		@SuppressWarnings("deprecation")
		@Override
		protected Boolean doInBackground(String... params) {
			// TODO Auto-generated method stub
			ByteArrayOutputStream bao = new ByteArrayOutputStream();
			if (photo != null) {
				photo.compress(Bitmap.CompressFormat.JPEG, 90, bao);
				HttpClient httpclient = MyApplication.httpClient;
				HttpPost httppost = new HttpPost(urlString);
				MultipartEntityBuilder builder = MultipartEntityBuilder
						.create();
				builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

				byte[] ba = bao.toByteArray();
				builder.addPart("userfile", new ByteArrayBody(ba, "temp.jpg"));
				// new StringBody(new
				// String(bao.toByteArray()),Charset.forName(HTTP.UTF_8)));
				HttpEntity entity = builder.build();
				httppost.setEntity(entity);

				HttpResponse httpResponse = null;
				try {
					httpResponse = httpclient.execute(httppost,
							MyApplication.localContext);
					if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
						// 取得返回的字符串
						String strResult = EntityUtils.toString(httpResponse
								.getEntity());
						Log.w("image", strResult);
						if (strResult.length() > 2) {
							JSONObject jhead = new JSONObject(strResult);
							statusString = jhead.getString("error");
						
								return true;
							
						}
					} else {
						Log.d("login", "wrong status");
						failString="服务器错误";
					}
				} catch (ClientProtocolException e) {
					Log.d("image", "protocol error");
					failString=e.toString();
				} catch (IOException e) {
					// TODO Auto-genLog.d("image","upload error");erated catch
					// block
					e.printStackTrace();
					failString="请检查网络链接"+e.toString();
					Log.d("image", "io error");
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Log.d("image", "json error");
					failString="服务器不给力呀：再试一次吧？"+e.toString();
				}
			}
			return false;
		}
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		getActivity();
		// 结果码不等于取消时候
		try {
			if (resultCode != 0) {

				switch (requestCode) {
				case IMAGE_REQUEST_CODE:
					startPhotoZoom(data.getData());
					break;
				case RESULT_REQUEST_CODE:
					if (data != null) {
						getImageToView(data);
					}
					break;
				}
			}
		} catch (Exception e) {
			Log.d("image", "null exception");
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	public void startPhotoZoom(Uri uri) {

		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 设置裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 180);
		intent.putExtra("outputY", 180);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, RESULT_REQUEST_CODE);
	}

	/**
	 * 保存裁剪之后的图片数据
	 * 
	 * @param picdata
	 */
	private void getImageToView(Intent data) {
		Bundle extras = data.getExtras();
		if (extras != null) {
			photo = extras.getParcelable("data");
			imageView.setImageBitmap(photo);
			uploadEnabled = true;
			modifyimage.setVisibility(View.VISIBLE);
		}
	}

}
